package com.pochogastos.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.pochogastos.model.Usuario;

/**
 * Servlet implementation class HomeServlet
 */
public class HomeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public HomeServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			if(request.getSession().getAttribute("ERROR_LOGIN")!=null)
				request.getSession().removeAttribute("ERROR_LOGIN");
			
			Usuario u = (Usuario)request.getSession().getAttribute("USUARIO");
			if(u==null){
				RequestDispatcher rd = getServletContext().getRequestDispatcher("/Login?accion=");
				rd.forward(request, response);
			}else{
				RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.jsp");
				rd.forward(request, response);	
			}
		} catch (Exception e) {
			e.printStackTrace();
			RequestDispatcher rd = getServletContext().getRequestDispatcher("/error.jsp");
			request.getSession().setAttribute("ERROR", e.getMessage());
			rd.forward(request, response);
		}
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			if(request.getSession().getAttribute("ERROR_LOGIN")!=null)
				request.getSession().removeAttribute("ERROR_LOGIN");
			
			Usuario u = (Usuario)request.getSession().getAttribute("USUARIO");
			if(u==null){
				RequestDispatcher rd = getServletContext().getRequestDispatcher("/Login?accion=");
				rd.forward(request, response);
			}else{
				RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.jsp");
				rd.forward(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			RequestDispatcher rd = getServletContext().getRequestDispatcher("/error.jsp");
			request.getSession().setAttribute("ERROR", e.getMessage());
			rd.forward(request, response);
		}
	}

}
